package cn.tedu.cwgl.service.impl;

import cn.tedu.cwgl.entity.House;
import cn.tedu.cwgl.entity.Role;
import cn.tedu.cwgl.entity.UserInfo;
import cn.tedu.cwgl.mapper.UserInfoMapper;
import cn.tedu.cwgl.service.UserInfoService;
import cn.tedu.cwgl.util.PageModel;
import cn.tedu.cwgl.util.Result;
import cn.tedu.cwgl.util.ResultUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class UserInfoServiceImpl implements UserInfoService {

    @Resource
    private UserInfoMapper userInfoMapper;

    @Override
    public UserInfo getUserInfo(UserInfo userInfo) {
        return userInfoMapper.getUserInfo(userInfo);
    }

    @Override
    public boolean userIsExisted(UserInfo userInfo) {
        return userInfoMapper.userIsExisted(userInfo) > 0 ? true : false;
    }

    @Override
    public int add(UserInfo userInfo) {
        // 添加用户
        int result = userInfoMapper.add(userInfo);
        System.out.println(userInfo);
        if (userInfo.getRoleid() == 2) {
            // 如果是家庭管理员，则新增家庭
            House house = new House();
            house.setOwnerid(userInfo.getId());
            int family = userInfoMapper.addHouseId(house);

            // 添加家庭成功后，绑定到该用户
            if (family == 1) {
                userInfo.setHouseid(house.getId().toString());
                result = userInfoMapper.update(userInfo);
            }
        }
        return result;
    }

    @Override
    public int addRole(Role role) {
        return userInfoMapper.addRole(role);
    }

    @Override
    public int update(UserInfo userInfo) {
        return userInfoMapper.update(userInfo);
    }

    @Override
    public List<Role> getAllRoles() {
        return userInfoMapper.getAllRoles();
    }

    @Override
    public List<Role> getRoles() {
        return userInfoMapper.getRoles();
    }

    @Override
    public Result getUsersByWhere(PageModel<UserInfo> model) {
        List<UserInfo> users = userInfoMapper.getUsersByWhere(model);
        if (users.size() >= 0) {
            Result<UserInfo> result = ResultUtil.success(users);
            result.setTotal(userInfoMapper.getTotalByWhere(model));
            if (result.getTotal() == 0) {
                result.setMsg("没有查到相关数据");
            } else {
                result.setMsg("数据获取成功");
            }
            return result;
        } else {
            return ResultUtil.unSuccess("没有找到符合条件的属性");
        }

    }

    @Override
    public int delete(UserInfo userInfo) {
        return userInfoMapper.delete(userInfo);
    }
}

